package com.flyqiu.form.core.storage;


import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.flyqiu.common.mybaits.plus.FlyQiuQueryWrapper;
import com.flyqiu.common.tools.FlyQiuCollectionTools;
import com.flyqiu.form.api.service.FlyQiuTableConfigService;
import com.flyqiu.form.api.store.FlyQiuAvueDynamicService;
import com.flyqiu.form.api.store.FlyQiuFormStoreManage;
import com.flyqiu.form.api.store.FlyQiuFormStoreService;
import com.flyqiu.form.api.tools.FlyQiuAvueColTools;
import com.flyqiu.form.common.exceptions.FlyQiuFormException;
import com.flyqiu.form.model.entity.FlyQiuTableConfig;
import org.apache.commons.lang3.StringUtils;

import java.util.List;
import java.util.function.Consumer;

import static com.flyqiu.form.common.FlyQiuFormConstant.FormBaseColumns.*;


public class FlyQiuAvueDynamicServiceImpl implements FlyQiuAvueDynamicService {


    private final FlyQiuFormStoreManage formStoreManage;
    private final FlyQiuTableConfigService flyQiuTableConfigService;

    public FlyQiuAvueDynamicServiceImpl(FlyQiuFormStoreManage formStoreManage, FlyQiuTableConfigService flyQiuTableConfigService) {
        this.formStoreManage = formStoreManage;
        this.flyQiuTableConfigService = flyQiuTableConfigService;
    }


    /**
     * 保存子表数据
     *
     * @param mainTableConfig 主表配置
     * @param mainDataId      主表数据id
     * @param data            需要保存的数据
     */
    public void save(FlyQiuTableConfig mainTableConfig, String mainDataId, JSONObject data) {
        if (StringUtils.isAllBlank(mainDataId)) {
            throw new FlyQiuFormException("主表数据不能为空");
        }
        if (data == null) {
            return;
        }
        handlerAvueDynamic(mainTableConfig, (dynamicTableConfig, dynamic, prop) -> {
            JSONArray dynamicData = data.getJSONArray(prop);
            saveToDynamicForm(dynamicTableConfig, mainDataId, dynamicData);
        });

    }

    private void saveToDynamicForm(FlyQiuTableConfig dynamicFormConfig, String mainDataId, JSONArray data) {
        if (data == null || data.isEmpty()) {
            return;
        }
        for (int i = 0; i < data.size(); i++) {
            JSONObject jsonObject = data.getJSONObject(i);
            saveToDynamicForm(dynamicFormConfig, mainDataId, jsonObject);
        }
    }

    private void saveToDynamicForm(FlyQiuTableConfig dynamicFormConfig, String mainDataId, JSONObject data) {
        data.put(COLUMN_MAIN_TABLE_ID, mainDataId);
        FlyQiuFormStoreService storeService = formStoreManage.getStoreService(dynamicFormConfig);
        storeService.save(dynamicFormConfig, data);
    }


    /**
     * 删除数据
     *
     * @param mainTableConfig 主表配置
     * @param mainDataId      主表数据id
     */
    @Override
    public void remove(FlyQiuTableConfig mainTableConfig, String mainDataId) {
        if (StringUtils.isAllBlank(mainDataId)) {
            throw new FlyQiuFormException("主表数据不能为空");
        }
        FlyQiuQueryWrapper FlyQiuQueryWrapper = new FlyQiuQueryWrapper();
        FlyQiuQueryWrapper.eq(COLUMN_MAIN_TABLE_ID, mainDataId);
        handlerAvueDynamic(mainTableConfig, (dynamicTableConfig, dynamic, prop) -> {
            dynamicTableRemove(dynamicTableConfig, FlyQiuQueryWrapper);
        });

    }

    private void dynamicTableRemove(FlyQiuTableConfig dynamicTableConfig, FlyQiuQueryWrapper queryWrapper) {
        FlyQiuFormStoreService storeService = formStoreManage.getStoreService(dynamicTableConfig);
        storeService.remove(dynamicTableConfig, queryWrapper);
    }

    /**
     * 修改数据
     *
     * @param mainTableConfig 主表配置
     * @param mainDataId      主表数据id
     * @param data            子表需要更新的数据
     */
    @Override
    public void update(FlyQiuTableConfig mainTableConfig, String mainDataId, JSONObject data) {
        if (StringUtils.isAllBlank(mainDataId)) {
            throw new FlyQiuFormException("主表数据不能为空");
        }

        handlerAvueDynamic(mainTableConfig, (dynamicTableConfig, dynamic, prop) -> {
            JSONArray dynamicData = data.getJSONArray(prop);
            if (dynamicData == null || dynamicData.isEmpty()) {
                return;
            }
            dynamicTableUpdate(dynamicTableConfig, mainDataId, dynamicData);
        });
    }

    private void dynamicTableUpdate(FlyQiuTableConfig dynamicTableConfig, String mainDataId, JSONArray dynamicTableData) {
        if (dynamicTableData == null || dynamicTableData.isEmpty()) return;
        FlyQiuQueryWrapper FlyQiuQueryWrapper = new FlyQiuQueryWrapper();
        FlyQiuQueryWrapper.eq(COLUMN_MAIN_TABLE_ID, mainDataId);
        dynamicTableRemove(dynamicTableConfig, FlyQiuQueryWrapper);
        saveToDynamicForm(dynamicTableConfig, mainDataId, dynamicTableData);
    }

    /**
     * 查询数据
     *
     * @param mainTableConfig 主表配置
     * @param mainData        主表数据id
     */
    @Override
    public void handlerDynamicSelect(FlyQiuTableConfig mainTableConfig, JSONObject mainData) {
        if (mainData == null || mainData.isEmpty()) {
            return;
        }
        FlyQiuQueryWrapper FlyQiuQueryWrapper = new FlyQiuQueryWrapper();
        FlyQiuQueryWrapper.eq(COLUMN_MAIN_TABLE_ID, mainData.getString(COLUMN_PK_NAME));
        FlyQiuQueryWrapper.orderByAsc(COLUMN_CREATE_TIME);
        FlyQiuFormStoreService storeService = formStoreManage.getStoreService(mainTableConfig);
        handlerAvueDynamic(mainTableConfig, (dynamicTableConfig, dynamic, prop) -> {
            List<JSONObject> list = storeService.list(dynamicTableConfig, FlyQiuQueryWrapper);
            mainData.put(prop, list);
        });
    }


    @Override
    public void syncDynamicTable(FlyQiuTableConfig mainTableConfig) {
        FlyQiuFormStoreService storeService = formStoreManage.getStoreService(mainTableConfig);
        handlerAvueDynamic(mainTableConfig, (dynamicTableConfig, dynamic, prop) -> storeService.synchronizationTable(dynamicTableConfig));

    }

    @Override
    public void deleteTable(FlyQiuTableConfig mainTableConfig) {
        if (StringUtils.isBlank(mainTableConfig.getId())) {
            return;
        }
        LambdaQueryWrapper<FlyQiuTableConfig> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(FlyQiuTableConfig::getParentId, mainTableConfig.getId());
        List<FlyQiuTableConfig> list = flyQiuTableConfigService.list(queryWrapper);

        FlyQiuCollectionTools.iterator(list, config -> {
            FlyQiuFormStoreService storeService = formStoreManage.getStoreService(mainTableConfig);
            storeService.deleteTable(config);
        });


    }

    /**
     * 处理表单总子表单创建同步逻辑
     *
     * @param mainFormConfig 主表单配置信息
     */
    private void handlerAvueDynamic(FlyQiuTableConfig mainFormConfig, HandlerDynamicTable handlerDynamicTable) {
        List<JSONObject> tableAvueDynamic = FlyQiuAvueColTools.getTableAvueDynamics(mainFormConfig);
        if (tableAvueDynamic == null || tableAvueDynamic.isEmpty()) return;
        JSONObject children;
        for (JSONObject dynamic : tableAvueDynamic) {
            children = dynamic.getJSONObject("children");
            if (!children.containsKey("column")) {
                continue;
            }
            if (children.getJSONArray("column").isEmpty()) {
                continue;
            }
            FlyQiuTableConfig dynamicFormConfig = FlyQiuAvueColTools.getAvueDynamicFormConfig(mainFormConfig, dynamic);
            handlerDynamicTable.handler(dynamicFormConfig, children, dynamic.getString("prop"));
        }
    }
}
